<template>
  <div class="routes">
    <!-- 搜索和操作栏 -->
    <el-card class="search-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchForm.path"
            placeholder="搜索路径"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchForm.method" placeholder="HTTP方法" clearable>
            <el-option label="GET" value="GET" />
            <el-option label="POST" value="POST" />
            <el-option label="PUT" value="PUT" />
            <el-option label="DELETE" value="DELETE" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchForm.enabled" placeholder="状态" clearable>
            <el-option label="启用" value="true" />
            <el-option label="禁用" value="false" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-col>
        <el-col :span="4" style="text-align: right">
          <el-button type="success" @click="handleAdd">新增路由</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 路由列表 -->
    <el-card class="table-card">
      <el-table :data="routes" style="width: 100%" v-loading="loading">
        <el-table-column prop="name" label="名称" min-width="120" />
        <el-table-column prop="path" label="路径" min-width="200" />
        <el-table-column prop="method" label="方法" width="100">
          <template #default="scope">
            <el-tag :type="getMethodTagType(scope.row.method)" size="small">
              {{ scope.row.method }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="templateName" label="模板" min-width="150" />
        <el-table-column prop="priority" label="优先级" width="80" />
        <el-table-column prop="statusCode" label="状态码" width="80" />
        <el-table-column prop="delayMs" label="延迟(ms)" width="100" />
        <el-table-column prop="enabled" label="状态" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.enabled"
              :active-value="true"
              :inactive-value="false"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="scope">
            {{ formatTime(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <el-button type="success" size="small" @click="handleRun(scope.row)">运行</el-button>
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="80%"
      top="3vh"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="路由名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入路由名称" />
        </el-form-item>
        <el-form-item label="路径" prop="path">
          <el-input v-model="form.path" placeholder="请输入路径，如: /api/users" />
        </el-form-item>
        <el-form-item label="HTTP方法" prop="method">
          <el-select v-model="form.method" placeholder="请选择HTTP方法">
            <el-option label="GET" value="GET" />
            <el-option label="POST" value="POST" />
            <el-option label="PUT" value="PUT" />
            <el-option label="DELETE" value="DELETE" />
          </el-select>
        </el-form-item>
        <el-form-item label="响应模板" prop="templateId">
          <el-select
            v-model="form.templateId"
            placeholder="请选择响应模板"
            filterable
            clearable
          >
            <el-option
              v-for="template in templates"
              :key="template.id"
              :label="template.name"
              :value="template.id"
            />
          </el-select>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="优先级" prop="priority">
              <el-input-number v-model="form.priority" :min="0" :max="100" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态码" prop="statusCode">
              <el-input-number v-model="form.statusCode" :min="200" :max="599" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="延迟(ms)" prop="delayMs">
              <el-input-number v-model="form.delayMs" :min="0" :max="10000" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="状态" prop="enabled">
          <el-switch
            v-model="form.enabled"
            :active-value="true"
            :inactive-value="false"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入路由描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 运行测试对话框 -->
    <el-dialog
      v-model="runDialogVisible"
      title="路由测试"
      width="70%"
      top="5vh"
    >
      <div v-if="currentRoute">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="路由名称">{{ currentRoute.name }}</el-descriptions-item>
          <el-descriptions-item label="路径">{{ currentRoute.path }}</el-descriptions-item>
          <el-descriptions-item label="HTTP方法">{{ currentRoute.method }}</el-descriptions-item>
          <el-descriptions-item label="状态码">{{ currentRoute.statusCode }}</el-descriptions-item>
          <el-descriptions-item label="延迟">{{ currentRoute.delayMs }}ms</el-descriptions-item>
          <el-descriptions-item label="优先级">{{ currentRoute.priority }}</el-descriptions-item>
        </el-descriptions>
        
        <el-divider />
        
        <el-form :model="runForm" label-width="100px">
          <el-form-item label="请求方法">
            <el-select v-model="runForm.method" style="width: 200px">
              <el-option label="GET" value="GET" />
              <el-option label="POST" value="POST" />
              <el-option label="PUT" value="PUT" />
              <el-option label="DELETE" value="DELETE" />
            </el-select>
          </el-form-item>
          <el-form-item label="请求头">
            <el-input
              v-model="runForm.headers"
              type="textarea"
              :rows="4"
              placeholder="请输入JSON格式的请求头，如: {&quot;Content-Type&quot;: &quot;application/json&quot;}"
            />
          </el-form-item>
          <el-form-item label="请求参数">
            <el-input
              v-model="runForm.params"
              type="textarea"
              :rows="4"
              placeholder="请输入JSON格式的请求参数，支持路径参数和URL参数。例如：&#10;路径参数：{&quot;id&quot;: 123} 用于替换 /api/{id}/user 中的 {id}&#10;URL参数：{&quot;page&quot;: 1, &quot;size&quot;: 10} 会拼接到URL后面"
            />
          </el-form-item>
          <el-form-item label="请求体">
            <el-input
              v-model="runForm.body"
              type="textarea"
              :rows="6"
              placeholder="请输入请求体内容"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="executeTest" :loading="testLoading">执行测试</el-button>
            <el-button @click="clearTestForm">清空表单</el-button>
            <el-button @click="runDialogVisible = false">关闭</el-button>
          </el-form-item>
        </el-form>
        
        <el-divider v-if="testResult" />
        
        <div v-if="testResult">
          <h4>测试结果</h4>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="请求URL" :span="2">
              <code>{{ testResult.requestUrl }}</code>
            </el-descriptions-item>
            <el-descriptions-item label="状态码">{{ testResult.statusCode }}</el-descriptions-item>
            <el-descriptions-item label="响应时间">{{ testResult.responseTime }}ms</el-descriptions-item>
            <el-descriptions-item label="响应头" :span="2">
              <pre>{{ formatJson(testResult.headers) }}</pre>
            </el-descriptions-item>
            <el-descriptions-item label="响应体" :span="2">
              <pre>{{ testResult.body }}</pre>
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { routeApi, templateApi } from '@/api'

export default {
  name: 'Routes',
  setup() {
    const loading = ref(false)
    const submitting = ref(false)
    const dialogVisible = ref(false)
    const dialogTitle = ref('')
    const routes = ref([])
    const templates = ref([])
    const formRef = ref()
    
    // 运行测试相关
    const runDialogVisible = ref(false)
    const currentRoute = ref(null)
    const testLoading = ref(false)
    const testResult = ref(null)

    // 搜索表单
    const searchForm = reactive({
      path: '',
      method: '',
      enabled: ''
    })

    // 分页信息
    const pagination = reactive({
      page: 1,
      size: 10,
      total: 0
    })

    // 表单数据
    const form = reactive({
      id: null,
      name: '',
      path: '',
      method: '',
      priority: 0,
      templateId: null,
      statusCode: 200,
      delayMs: 0,
      enabled: true,
      description: ''
    })

    // 运行测试表单数据
    const runForm = reactive({
      method: 'GET',
      headers: '{\n  "Content-Type": "application/json"\n}',
      params: '{\n  "id": 123\n}',
      body: ''
    })

    // 表单验证规则
    const rules = {
      name: [
        { required: true, message: '请输入路由名称', trigger: 'blur' }
      ],
      path: [
        { required: true, message: '请输入路径', trigger: 'blur' },
        { pattern: /^\/.+/, message: '路径必须以/开头', trigger: 'blur' }
      ],
      method: [
        { required: true, message: '请选择HTTP方法', trigger: 'change' }
      ],
      statusCode: [
        { required: true, message: '请输入状态码', trigger: 'blur' },
        { type: 'number', min: 200, max: 599, message: '状态码必须在200-599之间', trigger: 'blur' }
      ]
    }

    // 获取路由列表
    const fetchRoutes = async () => {
      loading.value = true
      try {
        const params = {
          page: pagination.page,
          size: pagination.size,
          ...searchForm
        }
        const response = await routeApi.getRoutes(params)
        if (response.code === 0) {
          routes.value = response.data.records || []
          pagination.total = response.data.total || 0
        } else {
          ElMessage.error(response.message || '获取路由列表失败')
        }
      } catch (error) {
        console.error('获取路由列表失败:', error)
      } finally {
        loading.value = false
      }
    }

    // 获取模板列表
    const fetchTemplates = async () => {
      try {
        const response = await templateApi.getAllTemplates()
        if (response.code === 0) {
          templates.value = response.data || []
        } else {
          console.error('获取模板列表失败:', response.message)
        }
      } catch (error) {
        console.error('获取模板列表失败:', error)
      }
    }

    // 搜索
    const handleSearch = () => {
      pagination.page = 1
      fetchRoutes()
    }

    // 重置搜索
    const handleReset = () => {
      Object.assign(searchForm, {
        path: '',
        method: '',
        enabled: ''
      })
      pagination.page = 1
      fetchRoutes()
    }

    // 新增路由
    const handleAdd = () => {
      dialogTitle.value = '新增路由'
      Object.assign(form, {
        id: null,
        name: '',
        path: '',
        method: '',
        priority: 0,
        templateId: null,
        statusCode: 200,
        delayMs: 0,
        enabled: true,
        description: ''
      })
      dialogVisible.value = true
    }

    // 编辑路由
    const handleEdit = (row) => {
      dialogTitle.value = '编辑路由'
      Object.assign(form, row)
      dialogVisible.value = true
    }

    // 删除路由
    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm('确定要删除这个路由吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await routeApi.deleteRoute(row.id)
        if (response.code === 0) {
          ElMessage.success('删除成功')
          fetchRoutes()
        } else {
          ElMessage.error(response.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除路由失败:', error)
        }
      }
    }

    // 状态切换
    const handleStatusChange = async (row) => {
      try {
        const response = await routeApi.updateRoute(row.id, { enabled: row.enabled })
        if (response.code === 0) {
          ElMessage.success('状态更新成功')
        } else {
          row.enabled = !row.enabled // 恢复原状态
          ElMessage.error(response.message || '状态更新失败')
        }
      } catch (error) {
        console.error('状态更新失败:', error)
        row.enabled = !row.enabled // 恢复原状态
      }
    }

    // 运行测试
    const handleRun = (row) => {
      currentRoute.value = row
      runForm.method = row.method
      
      // 自动填充示例参数
      const pathParams = row.path.match(/\{([^}]+)\}/g) || []
      if (pathParams.length > 0) {
        const exampleParams = {}
        pathParams.forEach(param => {
          const paramName = param.slice(1, -1) // 移除 { }
          exampleParams[paramName] = 123 // 示例值
        })
        runForm.params = JSON.stringify(exampleParams, null, 2)
      } else {
        runForm.params = '{\n  "page": 1,\n  "size": 10\n}'
      }
      
      runForm.headers = '{\n  "Content-Type": "application/json"\n}'
      runForm.body = '{\n  "example": "data"\n}'
      
      runDialogVisible.value = true
      testResult.value = null
    }

    // 执行测试
    const executeTest = async () => {
      if (!currentRoute.value) return
      
      testLoading.value = true
      try {
        // 解析请求头
        let headers = {}
        try {
          if (runForm.headers.trim()) {
            headers = JSON.parse(runForm.headers)
          }
        } catch (e) {
          ElMessage.warning('请求头格式错误，使用默认格式')
          headers = { 'Content-Type': 'application/json' }
        }
        
        // 解析请求参数
        let params = {}
        try {
          if (runForm.params.trim()) {
            params = JSON.parse(runForm.params)
          }
        } catch (e) {
          ElMessage.warning('请求参数格式错误，使用默认格式')
          params = {}
        }
        
        // 构建请求URL
        const baseUrl = window.location.origin
        let url = currentRoute.value.path
        
        // 处理路径参数替换
        url = url.replace(/\{([^}]+)\}/g, (match, paramName) => {
          if (params[paramName] !== undefined) {
            const value = params[paramName]
            // 从params中移除已使用的路径参数
            delete params[paramName]
            return encodeURIComponent(value)
          } else {
            ElMessage.warning(`缺少路径参数: ${paramName}`)
            return match
          }
        })
        
        // 处理URL参数拼接
        if (Object.keys(params).length > 0) {
          const queryParams = new URLSearchParams()
          Object.entries(params).forEach(([key, value]) => {
            if (value !== undefined && value !== null) {
              queryParams.append(key, value)
            }
          })
          const queryString = queryParams.toString()
          if (queryString) {
            url += (url.includes('?') ? '&' : '?') + queryString
          }
        }
        
        const finalUrl = `${baseUrl}${url}`
        console.log('测试URL:', finalUrl)
        
        const startTime = Date.now()
        
        // 发送请求
        const response = await fetch(finalUrl, {
          method: runForm.method,
          headers: headers,
          body: runForm.method !== 'GET' ? runForm.body : undefined
        })
        
        const responseTime = Date.now() - startTime
        const responseBody = await response.text()
        
        // 构建测试结果
        testResult.value = {
          statusCode: response.status,
          responseTime: responseTime,
          headers: Object.fromEntries(response.headers.entries()),
          body: responseBody,
          requestUrl: finalUrl
        }
        
        ElMessage.success('测试执行成功')
      } catch (error) {
        console.error('测试执行失败:', error)
        ElMessage.error('测试执行失败: ' + error.message)
      } finally {
        testLoading.value = false
      }
    }

    // 清空测试表单
    const clearTestForm = () => {
      runForm.headers = ''
      runForm.params = ''
      runForm.body = ''
      testResult.value = null
    }

    // 提交表单
    const handleSubmit = async () => {
      if (!formRef.value) return
      
      try {
        await formRef.value.validate()
        submitting.value = true
        
        if (form.id) {
          const response = await routeApi.updateRoute(form.id, form)
          if (response.code === 0) {
            ElMessage.success('更新成功')
          } else {
            ElMessage.error(response.message || '更新失败')
          }
        } else {
          const response = await routeApi.createRoute(form)
          if (response.code === 0) {
            ElMessage.success('创建成功')
          } else {
            ElMessage.error(response.message || '创建失败')
          }
        }
        
        dialogVisible.value = false
        fetchRoutes()
      } catch (error) {
        console.error('提交失败:', error)
      } finally {
        submitting.value = false
      }
    }

    // 对话框关闭
    const handleDialogClose = () => {
      if (formRef.value) {
        formRef.value.resetFields()
      }
    }

    // 分页处理
    const handleSizeChange = (size) => {
      pagination.size = size
      pagination.page = 1
      fetchRoutes()
    }

    const handleCurrentChange = (page) => {
      pagination.page = page
      fetchRoutes()
    }

    // 获取方法标签类型
    const getMethodTagType = (method) => {
      const typeMap = {
        GET: 'success',
        POST: 'primary',
        PUT: 'warning',
        DELETE: 'danger'
      }
      return typeMap[method] || 'info'
    }

    // 格式化时间
    const formatTime = (timestamp) => {
      return new Date(timestamp).toLocaleString('zh-CN')
    }

    // 格式化JSON
    const formatJson = (obj) => {
      try {
        return JSON.stringify(obj, null, 2)
      } catch {
        return String(obj)
      }
    }

    onMounted(() => {
      fetchRoutes()
      fetchTemplates()
    })

    return {
      loading,
      submitting,
      dialogVisible,
      dialogTitle,
      routes,
      templates,
      searchForm,
      pagination,
      form,
      rules,
      formRef,
      runDialogVisible,
      currentRoute,
      testLoading,
      testResult,
      runForm,
      handleSearch,
      handleReset,
      handleAdd,
      handleEdit,
      handleDelete,
      handleStatusChange,
      handleRun,
      executeTest,
      clearTestForm,
      handleSubmit,
      handleDialogClose,
      handleSizeChange,
      handleCurrentChange,
      getMethodTagType,
      formatTime,
      formatJson
    }
  }
}
</script>

<style scoped>
.routes {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 测试结果样式 */
pre {
  background-color: #f5f7fa;
  padding: 12px;
  border-radius: 4px;
  overflow-x: auto;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
  line-height: 1.4;
  margin: 0;
}

code {
  background-color: #f5f7fa;
  padding: 4px 8px;
  border-radius: 3px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
  color: #e6a23c;
}

.el-descriptions-item__label {
  font-weight: 600;
}
</style> 